/**
 * 本地存储管理模块
 * @module storage
 */

import { STORAGE_KEYS,DEFAULT_HEAD_POSITION } from './constants.js';

/**
 * 保存数据到本地存储
 * @param {string} key 存储键名
 * @param {*} value 存储值
 */
function saveToStorage(key, value) {
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
        console.error(`存储失败 (${key}):`, error);
    }
}

/**
 * 从本地存储加载数据
 * @param {string} key 存储键名
 * @param {*} defaultValue 默认值
 * @returns {*} 存储的值或默认值
 */
function loadFromStorage(key, defaultValue) {
    try {
        const value = localStorage.getItem(key);
        return value ? JSON.parse(value) : defaultValue;
    } catch (error) {
        console.error(`加载失败 (${key}):`, error);
        return defaultValue;
    }
}

/**
 * 清除所有图灵机相关存储
 */
function clearStorage() {
    Object.values(STORAGE_KEYS).forEach(key => {
        localStorage.removeItem(key);
    });
}

/**
 * 压缩状态数据并存储
 * @param {Object} state 图灵机状态
 */
export function compressAndStore(state) {
    const compressed = {
        t: state.tape,
        h: state.headPosition,
        b: state.byteSize,
        s: state.currentState,
        c: state.cache
    };
    saveToStorage(STORAGE_KEYS.TAPE, compressed);
}

/**
 * 从存储加载并解压状态数据
 * @returns {Object} 解压后的状态
 */
export function loadAndDecompress() {
    const data = loadFromStorage(STORAGE_KEYS.TAPE, null);
    if (!data) return null;

    return {
        tape: data.t || Array(DEFAULT_TAPE_LENGTH).fill('00'),
        headPosition: data.h || DEFAULT_HEAD_POSITION,
        byteSize: data.b || DEFAULT_BYTE_SIZE,
        currentState: data.s || DEFAULT_STATE,
        cache: data.c || []
    };
}

/**
 * 保存指令集到本地存储
 * @param {Array} instructions 指令集数组
 */
export function saveInstructions(instructions) {
    saveToStorage(STORAGE_KEYS.INSTRUCTIONS, instructions);
}

/**
 * 加载指令集
 * @returns {Array} 指令集数组
 */
export function loadInstructions() {
    return loadFromStorage(STORAGE_KEYS.INSTRUCTIONS, DEFAULT_INSTRUCTIONS);
}

/**
 * 添加执行历史记录
 * @param {Array} instruction 执行的指令
 * @param {number} step 步骤计数
 */
export function addHistory(instruction, step) {
    const history = loadFromStorage(STORAGE_KEYS.HISTORY, []);
    history.push({ step, instruction, timestamp: new Date().toISOString() });
    saveToStorage(STORAGE_KEYS.HISTORY, history.slice(-100)); // 只保留最近100条
}

/**
 * 清除执行历史
 */
export function clearHistory() {
    localStorage.removeItem(STORAGE_KEYS.HISTORY);
}

/**
 * 获取执行历史
 * @returns {Array} 历史记录数组
 */
export function getHistory() {
    return loadFromStorage(STORAGE_KEYS.HISTORY, []);
}

// 监听存储变化以实现多窗口同步
window.addEventListener('storage', (event) => {
    if (Object.values(STORAGE_KEYS).includes(event.key)) {
        window.dispatchEvent(new Event('turingMachineStorageUpdate'));
    }
});